<?php

$id     = $_GET['id'];
$pow    = $_GET['pow'];
$pulse  = $_GET['pulse'];

$s_day    = date('d');
$s_month  = date('m');
$s_year   = date('Y');
$s_sec    = date('s');
$s_min    = date('i');
$s_hour   = date('H');

$g_windowX = 120;
$g_windowY = 1000;
$g_zoom    = 50;

//==========================================
function fileContent($file)
//==========================================
{
	global $g_power;
  $handle = fopen($file, "r");
  if ($handle) {
	$kk=0;
    while (($line = fgets($handle)) !== false) {
        //echo("$line");
        $kk++;
        sscanf($line,"%d %d %d %f %d",$hour,$min,$sec,$pow,$puls);
        $xx = $hour*3600 + $min*60 + $sec;
        $g_power[$kk] = $pow;
    }
  } else {
    echo("error");
  } 
  fclose($handle);
  return($kk);
}
//==========================================
function readCurrentValue($file)
//==========================================
{

  if(!file_exists($file))
    {
      return("-");;
    }

  $in = fopen($file,"r");
  if($in)
    {
      $row = fgets($in);
    }  
  fclose($in);
  return($row);
}
//==========================================
function writeNewValue($file,$value)
//==========================================
{
  $out = fopen($file, 'w');
  fwrite($out,$value);
  fclose($out);
}
//==========================================
function prepareGraph($id)
//==========================================
{
  global $g_windowX,$g_windowY,$g_zoom;

  for($ii = 0;$ii<$g_windowY;$ii++)
  {
    for($jj = 0;$jj<=$g_windowX;$jj++)
    {
		$graphMatrix[$ii][$jj] = "&nbsp";
    }
  }
  
  $fileOut = 'graph-'.$id.'.bess'; 
  $out = fopen($fileOut, 'w');

  $fileIn = 'latest-'.$id.'.bess'; 
  $in = fopen($fileIn, 'r');
  if ($in) {
	$kk=0;
	$pmin = 10000;
	$pmax = 0;
    while (($line = fgets($in)) !== false) {
        sscanf($line,"%d %d %d %f",$temp1,$temp2,$temp3,$temp4);
        $kk++;
        if($temp4 > $pmax) $pmax = $temp4;
        if($temp4 < $pmin) $pmin = $temp4;
        $power[$kk] = $temp4;
    }
    $scale = ($pmax - $pmin)/$g_zoom;
    $up   = round($pmax/$scale);
    $down = round($pmin/$scale);
    $kmax = $kk;
    for($kk=0;$kk<=$kmax;$kk++)
    {
        $temp = round($power[$kk]/$scale);
        $graphMatrix[$temp][$kk] = '|';	
        for($ii=$down;$ii<$temp;$ii++)$graphMatrix[$ii][$kk] = '|';		
	}
  } 
  fclose($in);
  

  for($ii = $up;$ii>=$down;$ii--)
  {
	$nscale = round($ii*$scale);
	$stemp = sprintf("-%4d-",$nscale);
	fwrite($out,$stemp);
    for($jj = 0;$jj<=$g_windowX;$jj++)
    {
		fwrite($out,$graphMatrix[$ii][$jj]);
    }
    fwrite($out,$stemp);
    fwrite($out,"\n");
  }
  fclose($out);
}
//==========================================
function homeError($id,$msg)
//==========================================
{
	   $file = "home-error-".$id.".bess";  
	   $stamp = date(DATE_RFC822);
	   $out = fopen($file, 'a');
       if($out)
       {
         $content = $stamp." ".$msg."\n";fwrite($out,$content);
         fclose($out);	
       }
}
//==========================================
function readHomeConfig($id)
//==========================================
{
  global $g_windowX,$g_windowY,$g_zoom,$g_step,$g_tolerance,$g_threshold;
  $file = "home-config-".$id.".bess"; 
  $handle = fopen($file, "r");
  if ($handle) 
  {
    while (($line = fgets($handle)) !== false) 
    {
		if(strstr($line,"WINDOW:")) sscanf($line,"%s %d",$temp,$g_windowX);
		if(strstr($line,"ZOOM:")) sscanf($line,"%s %d",$temp,$g_zoom);
	    if(strstr($line,"STEP:")) sscanf($line,"%s %d",$temp,$g_step);
	    if(strstr($line,"TOLERANCE:")) sscanf($line,"%s %d",$temp,$g_tolerance);
		if(strstr($line,"THRESHOLD:")) sscanf($line,"%s %d",$temp,$g_threshold);
    }
    fclose($handle);
  } 
  else
  {
       $g_windowX   = 120;
       $g_windowY   = 1000;
       $g_zoom      = 50;	
       $g_step      = 3;
       $g_tolerance = 30;
       $g_threshold = 50;
       $out = fopen($file, 'w');
       if($out)
       {
         $content = "WINDOW:      ".$g_windowX."\n";fwrite($out,$content);
         $content = "ZOOM:        ".$g_zoom."\n";fwrite($out,$content); 
         $content = "STEP:        ".$g_step."\n";fwrite($out,$content);       
         $content = "TOLERANCE:   ".$g_tolerance."\n";fwrite($out,$content);       
         $content = "THRESHOLD:   ".$g_threshold."\n";fwrite($out,$content);             
         fclose($out);	
       }
       else
        homeError($id,"Unable to create default configuration");
  }
}

//==========================================
function consumerAnalysis($id,$file)
//==========================================
{
	global $g_power,$g_step,$g_tolerance,$g_threshold;
    $sim_length = fileContent($file);


      /* for($ii=2;$ii<$sim_length;$ii++)
       {
		   $left  = abs($g_power[$ii]-$g_power[$ii-1]);
		   $right = abs($g_power[$ii]-$g_power[$ii+1]);
	       if($right >= $left)$g_power[$ii] = $g_power[$ii-1];
	       if($right < $left)$g_power[$ii] = $g_power[$ii+1];
	   }*/
	   
	   for($ii=3;$ii<$sim_length-1;$ii++)
       {
           $temp = $g_power[$ii];
		   $left  = abs($g_power[$ii]-($g_power[$ii-1]+$g_power[$ii-2])/2);
		   $right = abs($g_power[$ii]-($g_power[$ii+1]+$g_power[$ii+2])/2);
	       if($right > $left)$g_power[$ii] = $g_power[$ii-1];
	       if($right < $left)$g_power[$ii] = $g_power[$ii+1];
	       //cho("$ii $temp $g_power[$ii] \n");
	   }
	   
     	$kk   = 0;
        $kmax = 0;
        
        $delta = $g_power[$ii] - $g_power[$ii-1];

        for($ii=2;$ii<=$sim_length;$ii=$ii+1)
        {
	       $delta = $g_power[$ii] - $g_power[$ii-1];
	       $watt = abs($delta);
	       if($delta > 0 && $watt > $g_threshold) 
	       {
	        	$kk++;
	        	$kmax++;
	        	$consumer[$kmax] = $watt;
	            //echo("$ii $g_power[$ii] $delta START\n");
	       }
           else if($delta < 0 && $watt > $g_threshold) 
	       {
	        	for($mm=1;$mm<=$kmax;$mm++)
	        	{
	         	  if(abs($consumer[$mm] - $watt) < $g_tolerance)
	        	  {
	        		  $consumer[$mm] = 0;
	        		  $kk--;
	        		  //echo("ii=$ii mm=$mm $g_power[$ii] $delta END\n");
		          }
	            }
	       }
	       //else
	       	       //echo("$ii $g_power[$ii] $delta ----\n");
        }

  $file = 'consumer-'.$id.".bess"; 
  $out = fopen($file, 'w');
  fwrite($out,"Current = $kk Max = $kmax  Tolerance = $g_tolerance Threshold = $g_threshold\n");
  $nn = 0;
  for($ii=1;$ii<=$kmax;$ii++)
  {
	if($consumer[$ii] != 0)
	{
		$nn++;
		fwrite($out,"$nn Consumer $ii $consumer[$ii]\n");
	}
  }
  fclose($out);
}
//==========================================
//==========================================
// Main
//==========================================
if($id > 999 && $id < 10000) // Valid client id
  {
	// Read configuration
	readHomeConfig($id);
	
	// Log data 
    $file1 = "data-".$id.'-'.$s_year.'-'.$s_month.'-'.$s_day.".bess"; 
    $out = fopen($file1, 'a');
    $data = $s_hour." ".$s_min." ".$s_sec." ".$pow." ".$pulse."\n";
    fwrite($out, $data); 
    fclose($out);
    
    // Update accumulated kWh per diem
    $file4 = "kwh-".$id.'-'.$s_year.'-'.$s_month.'-'.$s_day.".bess"; 
    $value = readCurrentValue($file4);
    $value = $value + $pulse;
    writeNewValue($file4,$value);
    
    // Write latest power to file
    $file2 = 'pow-'.$id.".bess"; 
    $out = fopen($file2, 'w');
    $data = $pow." Watt\n";fwrite($out, $data); 
    fclose($out); 
    
    // Write latest date and time to file
    $file3 = 'time-'.$id.".bess"; 
    $out = fopen($file3, 'w');
    $data = $s_year."-"; fwrite($out, $data); 
    $data = $s_month."-";fwrite($out, $data); 
    $data = $s_day."   ";fwrite($out, $data); 
    $data = $s_hour.":"; fwrite($out, $data); 
    $data = $s_min.":";  fwrite($out, $data); 
    $data = $s_sec."\n"; fwrite($out, $data); 
    fclose($out); 
    
    // Extract latest values from log to file
    system("tail -n $g_windowX $file1 > latest-$id.bess");
    
    // Prepare latest graph file
    prepareGraph($id);
    consumerAnalysis($id,$file1);
  }
  //==========================================
?>
